package com.shelpe.services.algorithm.semiauto;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shelpe.services.algorithm.entity.batis.Keyword;
import com.shelpe.services.algorithm.entity.batis.KeywordExample;
import com.shelpe.services.algorithm.entity.batis.RptKeyword;
import com.shelpe.services.algorithm.repository.batis.KeywordMapper;
import com.shelpe.services.algorithm.repository.batis.RptKeywordMapper;
import com.shelpe.services.algorithm.repository.dto.semiauto.SemiautoCondition;
import com.shelpe.services.algorithm.utils.SemiautoUtils;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class MaxSemiautoConditionsInitializer implements SemiautoConditionsInitializer {
	@Autowired
	private RptKeywordMapper rptKeywordMapper;
	@Autowired
	private KeywordMapper keywordMapper;
	
	@Override
	public void run(SemiautoCondition condition, Context context) {
		if(condition.getSourceType() != SemiautoCondition.SOURCE_TYPE_MAX){
			return;
		}
		if(context.getMaxData() == null){
			SemiautoData data = new SemiautoData();
			
			Date yesterday = DateUtils.addDays(DateUtils.truncate(new Date(), Calendar.DATE), -1);
			int lower = 1;
			int upper = 2;
			if(context.isMobile()){
				lower = 3;
				upper = 4;
			}
			List<RptKeyword> reports = this.rptKeywordMapper.reportAverage(context.getAdgroupID(), context.getUserID(), 
					DateFormatUtils.format(DateUtils.addDays(yesterday, - context.getInterval()), DateFormatUtils.format(yesterday, "yyyy-MM-dd")), 
					DateFormatUtils.format(yesterday, DateFormatUtils.format(yesterday, "yyyy-MM-dd")),
					lower, upper);
			if(reports != null && reports.size() > 0){
				RptKeyword wordData = reports.get(0);
				BeanUtils.copyProperties(wordData, data);
			}
			
			KeywordExample exmaple = new KeywordExample();
			exmaple.setUserId(context.getUserID());
			exmaple.createCriteria().andAdgroupIdEqualTo(context.getAdgroupID());
			List<Keyword> keywords = this.keywordMapper.selectByExample(exmaple);
			int qscore = 0;
			int wirelessQscore = 0;
			for(Keyword kw: keywords){
				qscore = Math.max(qscore, kw.getQscore());
				wirelessQscore = Math.max(wirelessQscore, kw.getWirelessQscore());
			}
			data.setQscore(qscore);
			data.setWirelessQscore(wirelessQscore);
			
			log.debug("data: {}", data);
			context.setMaxData(data);
		}
		
		
		if(condition.getName() != null && context.getMaxData() != null){
			float value = SemiautoUtils.pickup(condition.getName(), context.getMaxData());
			log.debug("pick up {} value: {}", condition.getName() , value);
			condition.setSourceValue(value + "");
		}
	}

}
